package com.sqx.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.*;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpTakeService;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class UserMoneyServiceImpl extends ServiceImpl<UserMoneyDao, UserMoney> implements UserMoneyService {
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private UserVipDao userVipDao;
    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private HelpTakeService takeService;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public void updateMoney(int i, Long userId, BigDecimal money) {
        UserMoney userMoney = selectUserMoneyByUserId(userId);
        baseMapper.updateMayMoney(i, userId, money);
    }

    @Override
    public UserMoney selectUserMoneyByUserId(Long userId) {
        UserMoney userMoney = baseMapper.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
        if (userMoney == null) {
            userMoney = new UserMoney();
            userMoney.setUserId(userId);
            userMoney.setMoney(BigDecimal.ZERO);
            userMoney.setSafetyMoney(BigDecimal.ZERO);
            baseMapper.insert(userMoney);
        }
        return userMoney;
    }

    @Override
    public Double selectMyProfit(Long userId) {

        return userMoneyDetailsDao.selectMyProfit(userId);
    }

    @Override
    public synchronized Result payTakingOrder(Long userId, Long orderId) {
        //时间类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查看订单
        Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_id", orderId));
        if (orders == null) {
            return Result.error("订单不存在！");
        } else {
            //如果是接单订单
            if (orders.getOrdersType() == 1) {
                if (orders.getState().equals("1")) {
                    return Result.error("订单进行中！");
                } else if (orders.getState().equals("2")) {
                    return Result.error("订单已完成！");
                } else if (orders.getState().equals("3")) {
                    return Result.error("订单已退款！");
                } else {
                    //订单状态为待支付
                    //查看用户账户余额
                    UserMoney userMoney = selectUserMoneyByUserId(userId);
                    if (userMoney == null) {
                        return Result.error("用户钱包信息不存在！");
                    } else {
                        //用户余额
                        BigDecimal money = userMoney.getMoney();
                        int i = money.compareTo(orders.getPayMoney());
                        if (i >= 0) {
                            //修改我的的余额
                            baseMapper.updateMayMoney(2, userId, orders.getPayMoney());
                            //设置订单状态
                            orders.setState("1");
                            //设置更新时间
                            orders.setUpdateTime(simpleDateFormat.format(new Date()));
                            //更新到订单表中
                            ordersDao.updateById(orders);
                            return Result.success("支付成功!");

                        } else {
                            return Result.error("余额不足!");
                        }
                    }
                }
            } else {
                //会员订单
                if (orders.getState().equals("1")) {
                    return Result.error("订单进行中！");
                } else if (orders.getState().equals("2")) {
                    return Result.error("订单已完成！");
                } else if (orders.getState().equals("3")) {
                    return Result.error("订单已退款！");
                } else {
                    //订单的状态为待支付
                    //查看用户账户余额
                    UserMoney userMoney = selectUserMoneyByUserId(userId);
                    //用户余额
                    BigDecimal money = userMoney.getMoney();
                    int i = money.compareTo(orders.getPayMoney());
                    if (i >= 0) {

                        //修改我的的余额
                        baseMapper.updateMayMoney(2, userId, orders.getPayMoney());
                        return setMember(orders,userId);
                    } else {
                        return Result.error("余额不足!");
                    }
                }
            }

        }
    }

    @Override
    public Result setMember(Orders orders,Long userId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long vipTypeId = orders.getVipDetailsId();
        //查看要开通会员类型
        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", vipTypeId));
        UserEntity userEntity = userService.selectUserById(userId);
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        MessageInfo messageInfo = new MessageInfo();
        userMoneyDetails.setMoney(orders.getPayMoney());
        userMoneyDetails.setUserId(orders.getUserId());
        if ((vipDetails.getVipNameType().equals(0))) {
            //月
            userMoneyDetails.setContent("开通月卡会员");
            messageInfo.setContent("开通会员成功");
        } else if ((vipDetails.getVipNameType()).equals(1)) {
            //季
            userMoneyDetails.setContent("开通季卡会员");
            messageInfo.setContent("开通会员成功");
        } else {
            //年
            userMoneyDetails.setContent("开通年费会员");
            messageInfo.setContent("开通会员成功");
        }
        userMoneyDetails.setTitle("开通会员");
        userMoneyDetails.setType(2);
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        messageInfo.setTitle("开通会员");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        if (StringUtil.isNotBlank(userEntity.getClientid())) {
            userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
        }


        //设置订单状态
        orders.setState("2");
        //设置更新时间
        orders.setUpdateTime(simpleDateFormat.format(new Date()));
        //更新到订单表中
        ordersDao.updateById(orders);
        //查看会员类型

        //查看用户是否是会员
        UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        //日历
        Calendar cal = Calendar.getInstance();
        if (userVip != null) {
            userVip.setIsVip(1);
            //是会员
            //查看会员到期时间
            Date endDate = null;
            try {
                endDate = simpleDateFormat.parse(userVip.getEndTime());
            } catch (Exception e) {
                e.getMessage();
            }
            //查看会员是否到期
            if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) {
                //没有到期
                if (vipDetails != null) {
                    //设置会员到期时间到日历
                    cal.setTime(endDate);
                    //判断会员的续费时间
                    if ((vipDetails.getVipNameType().equals(0))) {
                        //月
                        cal.add(Calendar.MONTH, 1);
                    } else if ((vipDetails.getVipNameType()).equals(1)) {
                        //季
                        cal.add(Calendar.MONTH, 3);
                    } else {
                        //年
                        cal.add(Calendar.YEAR, 1);
                    }
                    //设置会员的到期时间
                    userVip.setEndTime(simpleDateFormat.format(cal.getTime()));
                    //更新会员信息
                    userVipDao.updateById(userVip);
                    //填写邀请码则奖励金币 没有则不奖励
                    addMoney(userId, vipDetails);
                    return Result.success("开通成功！");
                } else {
                    return Result.error("会员类型详情为空！");
                }
                //没有开通过会员 或会员已经到期
            } else {
                //到期了
                //将现在的时间设置到日历中去
                cal.setTime(new Date());
                //判断会员续费的时间
                if ((vipDetails.getVipNameType()).equals(0)) {
                    //月
                    cal.add(Calendar.MONTH, 1);
                } else if ((vipDetails.getVipNameType()).equals(1)) {
                    //季
                    cal.add(Calendar.MONTH, 3);
                } else {
                    //年
                    cal.add(Calendar.YEAR, 1);
                }
                //设置会员的到期时间
                userVip.setEndTime(simpleDateFormat.format(cal.getTime()));
                //更新会员信息
                userVipDao.updateById(userVip);
                //填写邀请码则奖励金币 没有则不奖励
                addMoney(userId, vipDetails);
                return Result.success("开通成功！");
            }

        } else {
            //不是会员
            //创建会员对象
            UserVip userVip1 = new UserVip();
            //设置会员类型
            userVip1.setVipNameType(vipDetails.getVipNameType());
            //设置开通会员的用户id
            userVip1.setUserId(userId);
            //设置会员的购买时间
            userVip1.setCreateTime(simpleDateFormat.format(new Date()));
            //将现在时间设置到日历中
            cal.setTime(new Date());
            //判断会员的续费时间
            if ((vipDetails.getVipNameType()).equals(0)) {
                //月
                cal.add(Calendar.MONTH, 1);
            } else if ((vipDetails.getVipNameType()).equals(1)) {
                //季
                cal.add(Calendar.MONTH, 3);
            } else {
                //年
                cal.add(Calendar.YEAR, 1);
            }
            //设置会员的到期时间
            userVip1.setEndTime(simpleDateFormat.format(cal.getTime()));
            userVip1.setIsVip(1);
            //设置会员
            userVipDao.insert(userVip1);
            //填写邀请码则奖励金币 没有则不奖励
            addMoney(userId, vipDetails);
        }
        return Result.success("开通成功！");
    }





    @Override
    public PageUtils balanceDetailed(Long userId, Page<UserMoneyDetails> pages) {
        return new PageUtils(userMoneyDetailsDao.selectPage(pages, new QueryWrapper<UserMoneyDetails>().eq("user_id", userId).orderByDesc("create_time").isNull("classify")));
    }

    @Override
    public Result profitDetailed(Long userId, IPage ipage) {
        //收益明细
        return null;
    }

    @Override
    public int updateSafetyMoney(Integer type, Long userId, BigDecimal money) {
        return baseMapper.updateSafetyMoney(type, userId, money);
    }

    @Override
    public void safetyMoneyCallback(PayDetails payDetails) {
        baseMapper.updateSafetyMoney(1, payDetails.getUserId(), BigDecimal.valueOf(payDetails.getMoney()));
        UserEntity userEntity = userService.getById(payDetails.getUserId());
        UserMoney userMoney = baseMapper.selectOne(new QueryWrapper<UserMoney>().eq("user_id", payDetails.getUserId()));
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setClassify(5);
        userMoneyDetails.setUserId(payDetails.getUserId());
        userMoneyDetails.setType(1);
        userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
        userMoneyDetails.setTitle("缴纳保证金");
        userMoneyDetails.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        userMoneyDetails.setContent("缴纳保证金金额" + payDetails.getMoney() + "元,当前保证金" + userMoney.getSafetyMoney() + "元");
        userMoneyDetailsDao.insert(userMoneyDetails);
        CommonInfo safetyMoney = commonInfoService.findOne(616);
        if (userMoney.getSafetyMoney().compareTo(new BigDecimal(safetyMoney.getValue())) >= 0) {
            userEntity.setIsSafetyMoney(1);
        } else {
            userEntity.setIsSafetyMoney(0);
        }
        userService.updateById(userEntity);
    }

    @Override
    public Result refundSafetMoney(Long userId) {
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        reentrantReadWriteLock.writeLock().lock();
        try {
            UserEntity userEntity = userService.selectUserById(userId);
            if (userMoney.getSafetyMoney()==null || userMoney.getSafetyMoney().compareTo(BigDecimal.ZERO)==0) {
                return Result.error("当前账号未缴纳保证金！");
            }
            //判断当前是否有进行中的订单
            int takeCount = takeService.count((new QueryWrapper<HelpTake>().in("status", 1, 2).eq("user_id", userId)));
            int ordersCount = ordersDao.selectCount((new QueryWrapper<Orders>().in("state", 1, 4).eq("order_taking_user_id", userId)));
            if (takeCount > 0 || ordersCount > 0) {
                return Result.error("当前账户有未完成的订单，请完成后再进行退还！");
            }
            BigDecimal money = userMoney.getSafetyMoney();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(new Date());
            userMoneyService.updateMoney(1, userId, money);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("[保证金]退还保证金");
            userMoneyDetails.setContent("退还保证金,转入余额：" + money + "元");
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetailsService.save(userMoneyDetails);

            userMoneyService.updateSafetyMoney(2, userId, money);
            userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setClassify(5);
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("[保证金]退还保证金");
            userMoneyDetails.setContent("退还保证金，保证金减少：" + money);
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(time);
            userMoneyDetailsService.save(userMoneyDetails);
            userEntity.setIsSafetyMoney(0);
            userService.updateById(userEntity);

            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public IPage<UserMoneyDetails> getBondDetails(Long userId, Integer page, Integer limit, UserMoneyDetails userMoneyDetails) {
        userMoneyDetails.setUserId(userId);
        Page<UserMoneyDetails> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        QueryWrapper<UserMoneyDetails> wrapper = new QueryWrapper<UserMoneyDetails>().eq("classify", 5);
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        wrapper.orderByDesc("create_time");
        IPage<UserMoneyDetails> selectPage = userMoneyDetailsDao.selectPage(pages, wrapper);
        for (UserMoneyDetails record : selectPage.getRecords()) {
            UserEntity userEntity = userService.getById(record.getUserId());
            if (userEntity != null) {
                record.setUserName(userEntity.getUserName());
            }

        }
        return selectPage;
    }

    @Override
    public HashMap<String, Object> getSafetyMoneyData(Integer flag, String time) {

        HashMap<String, Object> hashMap = new HashMap<>();
        BigDecimal safetyMoney = baseMapper.getSafetyMoneyData(flag, time);
        hashMap.put("safetyMoney", safetyMoney);
        return hashMap;


    }

    /**
     * 开通成功会员后  奖励金币
     *
     * @param userId
     * @param
     */
    public void addMoney(Long userId, VipDetails vipDetails) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //是否填写过邀请码
        UserEntity userEntity = userDao.selectById(userId);
        if (userEntity.getInviterCode() != null) {
            //查询填写邀请码的所属人
            UserEntity user = userDao.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", userEntity.getInviterCode()));
            if (user != null) {
                //创建钱包详情模板
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                //设置收益人
                userMoneyDetails.setUserId(user.getUserId());
                //设置购买人
                userMoneyDetails.setByUserId(userId);
                //设置类型
                userMoneyDetails.setType(1);
                //设置title
                userMoneyDetails.setTitle("邀请用户购买会员");
                //设置创建时间
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                //填写过邀请码
                userMoneyDetails.setMoney(vipDetails.getAward());
                //设置内容
                userMoneyDetails.setContent("邀请用户购买会员奖励：" + vipDetails.getAward());
                userMoneyDetailsDao.insert(userMoneyDetails);
                //将奖励的金币添加到受益人的钱包里
                baseMapper.updateMayMoney(1, user.getUserId(), vipDetails.getAward());

                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("邀请用户购买会员奖励：" + vipDetails.getAward());
                messageInfo.setTitle("邀请用户购买会员");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(user.getUserName());
                messageInfo.setUserId(String.valueOf(user.getUserId()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                messageInfo.setCreateAt(sdf.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                if (StringUtils.isNotEmpty(user.getClientid())) {
                    userService.pushToSingle("邀请用户购买会员", "邀请用户购买会员奖励：" + vipDetails.getAward(), user.getClientid());
                }
                log.info("奖励成功！");
            }

        } else {
            log.error("没有填写过邀请码 无法奖励");
        }
    }
}
